package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.config.AliPayConfig;
import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.constant.OrderConstants;
import cn.itsource.ymcc.constant.PayConstants;
import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.CourseOrderItem;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.exception.GlobalException;
import cn.itsource.ymcc.mapper.PayOrderMapper;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@RocketMQMessageListener(consumerGroup = "service-pay-timeout-consumer",
        //Topic
        topic = PayConstants.MQ_TOPIC_PAYORDER_TIMEOUT_PAYORDER,
         //TAGS
        selectorExpression = PayConstants.MQ_TAGS_PAYORDER_TIMEOUT_PAYORDER
)
@Slf4j
public class PayTimeOutConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private PayOrderMapper payOrderMapper;

    @Autowired
    private AliPayConfig aliPayConfig;
    @Override
    public void onMessage(MessageExt message) {

        try {
            byte[] body = message.getBody();
            String orderNo = new String(body, Constants.UTF8);
            PayOrder payOrder = payOrderMapper.selectOne(new LambdaQueryWrapper<PayOrder>().eq(PayOrder::getOrderNo, orderNo));
            payOrder.setPayStatus(RConst.Num.INT_2);
            payOrderMapper.updateById(payOrder);

            System.out.println("支付单超时更改状态成功");
            //向支付宝去发送请求进行关单
            String code = aliPayConfig.closePayOrder(orderNo);
            if (code.equals(RConst.Str.NUM_10000)){
               log.info("-----------支付宝关单成功");
            }else {
                log.error("-----------支付宝关单失败");
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobalException("支付单超时更改状态失败");
        }
    }
}